import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()

export class HeroService {
    constructor(private http: Http) { }

    getHeroesSlowly(): Promise<Hero[]> {
        return new Promise(resolve => {
            // Simulate server latency with 2 second delay
            setTimeout(() => resolve(this.getHeroes()), 2000);
        });
    };
    getHero(id: number): Promise<Hero> {
        const url = `${this.heroesUrl}/${id}`;
        return this.http.get(url)
            .toPromise()
            // .then(response => {
            //     Promise.resolve(response.json());
            //      ;//as Hero
            // })
             .then(response =>response.json())
            .catch(this.handleError);
    };
    private heroesUrl = 'api/heroes';  // URL to web api
    getHeroes(): Promise<Hero[]> {
        // return Promise.resolve( [
        //     { id: 11, name: 'Mr. Nice' },
        //     { id: 12, name: 'Narco' },
        //     { id: 13, name: 'Bombasto' },
        //     { id: 14, name: 'Celeritas' },
        //     { id: 15, name: 'Magneta' },
        //     { id: 16, name: 'RubberMan' },
        //     { id: 17, name: 'Dynama' },
        //     { id: 18, name: 'Dr IQ' },
        //     { id: 19, name: 'Magma' },
        //     { id: 20, name: 'Tornado' }
        //   ]);

       return this.http.get(this.heroesUrl).toPromise()
       .then(response => response.json() as Hero[])
            // .then(response => {
            //     var data = response.json() as Hero[];
            //     Promise.resolve(data);
            // })
            .catch(this.handleError);
    };
    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    };

    private headers = new Headers({ 'Content-Type': 'application/json' });
    update(hero: Hero): Promise<Hero> {
        const url = `${this.heroesUrl}/${hero.id}`;
        return this.http.put(url, JSON.stringify(hero), { headers: this.headers })
            .toPromise().then(() => hero).catch(this.handleError);
    };
    create(name: string): Promise<Hero> {
        return this.http
            .post(this.heroesUrl, JSON.stringify({ name: name }), { headers: this.headers })
            .toPromise()
            .then(res => res.json().data as Hero)
            .catch(this.handleError);
    };
    delete(id: number): Promise<void> {
        const url = `${this.heroesUrl}/${id}`;
        return this.http.delete(url, { headers: this.headers })
            .toPromise()
            .then(() => null)
            .catch(this.handleError);
    }
}